-- UIRelicStrengthenDetail
-- Create by cheny
-- 强化详细界面

--UIRelicStrengthenDetail继承自Layer
UIRelicStrengthenDetail = class("UIRelicStrengthenDetail", function()
    return cc.Layer:create();
end);

function UIRelicStrengthenDetail.create(info)
    return UIRelicStrengthenDetail.new(info);
end

-- 构造函数
function UIRelicStrengthenDetail:ctor(info)
    self:setName("UIRelicStrengthenDetail");
    self.info = info;

    -- 初始化
    local node = cc.CSLoader:createNode("layout/workshop/StrengthenDetail.csb");
    self:addChild(node);
    self.node = node;

    -- 注册点击事件
    self:registerTouchEvent();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    self.costParentNode = findChildByName(self.node, "CT/cost");
    self.originCostParentPosX = self.costParentNode:getPositionX();
    self.originCostParentPosY = self.costParentNode:getPositionY();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 注册事件处理回调函数
function UIRelicStrengthenDetail:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            EventMgr.removeAll("UIRelicStrengthenDetail");
        elseif eventType == "enter" then

        end
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UIRelicStrengthenDetail", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIRelicStrengthenDetail" then
            if self.info["rule"] == "ariship_skill" then
                UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_FIRST_RUINS_SCRAP, TOPMENU_FRAME_GEM);
            else
                UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_RUINS_SCRAP);
            end
        elseif para["lose"] == "UIAwakeMain" then

        end
    end);

    -- 可能会直接购买碎片
    EventMgr.register("UIRelicStrengthenDetail", event.DIRECT_BUY_GOODS, function(args)
        -- 提示购买的数量
        alertBuyGoodsTip(args.bonus);
        self:redraw(true);
    end);
end

-- 注册点击事件
function UIRelicStrengthenDetail:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIRelicStrengthenDetail");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册强化按钮点击事件
    local btnBuy = findChildByName(self.node, "CT/strengthen");
    local function onBuyClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            local id = self.info.id;
            local ret = SkyRelicFunctionM.canDevelop(id);
            if ret ~= true then
                local tip, requireAmount = SkyRelicFunctionM.canDevelopDetail(id);
                if tip ~= "" then
                    if tip == "not_enough_gem_to_strengthen" then
                        -- 钻石不足
                        showGemLackConfirm();
                        return;
                    elseif tip == "relic_scrap_lack" then
                        showScrapLackConfirm(requireAmount);
                        return;
                    elseif tip == "money_lack" then
                        showMoneyLackConfirm(requireAmount);
                        return;
                    end

                    -- 弹字
                    alert(extractString(tip));
                end
                return;
            end

            -- 强化炼金项后续处理
            local function addEffect()
                local uiForm = UIMgr.getCurrentScene():getFormByName("UIRelicStrengthen");
                if uiForm then
                    uiForm:playStrengthenEffect(id);
                end

                -- 关闭界面
                UIMgr.getCurrentScene():removeFormByName("UIRelicStrengthenDetail");
            end

            local gemCost = self:calcStrengthenGemCost(id);
            if gemCost > 0 then
                -- 如果需要花费钻石，则弹出确认提示框
                local level = SkyRelicFunctionM.getLevel(id);
                local msg = string.format(getLocStr("strengthen_confirm"), gemCost, level + 1);
                local title = SkyRelicFunctionM.query(id, "name");

                local function callback()
                    -- 升级
                    SkyRelicFunctionM.develop(id);
                    -- 后续处理
                    addEffect();
                end

                local function cancelCallBack()
                    -- 关闭界面
                    UIMgr.getCurrentScene():removeFormByName("UIStrengthenDetail");
                end

                confirm2(CONFIRM_TYPE_OK, title, msg, callback,
                    cancelCallBack, getLocStr("btn_text_intensify"));
            else
                -- 升级
                SkyRelicFunctionM.develop(id)
                -- 后续处理
                addEffect();
            end
        end
    end
    btnBuy:addTouchEventListener(onBuyClick);
    TextStyleM.setTextStyle(btnBuy, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
end

-- 计算强化的钻石消耗
function UIRelicStrengthenDetail:calcStrengthenGemCost(id)
    local cost = SkyRelicFunctionM.calcCost(id);

    for classId, count in pairs(cost) do
        if type(classId) == "string" and classId == "gem" then
            return count;
        end
    end

    return 0;
end

-- 界面重绘
function UIRelicStrengthenDetail:redraw(notAjust)
    local id = self.info.id;
    -- 当前等级
    local level = SkyRelicFunctionM.getLevel(id);
    local maxLevel = self.info.max_level;

    -- 强化按钮
    local btnBuy = findChildByName(self.node, "CT/strengthen");
    local levelStr;
    local titleStr = getLocStr("btn_text_strengthen");
    if level >= maxLevel then
        levelStr = getLocStr("level_max");
    else
        levelStr = string.format(getLocStr("level_flag"), level + 1);
    end
    btnBuy:setTitleText(titleStr .. " " .. levelStr);

    -- 是否是星阶限制的
    local rankLimit = SkyRelicFunctionM.checkRankLimit(id);
    if level >= maxLevel or rankLimit then
        setButtonEnabled(btnBuy, false);
    else
        setButtonEnabled(btnBuy, true);
    end

    -- 设置标题样式
    local titleLabel = findChildByName(self.node, "CT/template/title");
    titleLabel:setString(SkyRelicFunctionM.query(id, "name"));
    TextStyleM.setTitleStyle(titleLabel);

    -- 道具描述1
    local desc1Label = findChildByName(self.node, "CT/desc1");
    local desc = SkyRelicFunctionM.getStrengthenDesc(id);
    TextStyleM.setTextStyle(desc1Label,TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    applyString(desc1Label, desc);

    -- 图标
    local item = findChildByName(self.node, "CT/item");
    local icon = item:getChildByName("icon");
    local fileName = SkyRelicFunctionM.query(id, "icon");

    local rule = SkyRelicFunctionM.query(id, "rule");
    local condition = SkyRelicFunctionM.query(id, "condition");

    -- 勋章的话直接取用物品图标
    if rule == "sky_medal" then
        local medalId = SkyRelicFunctionM.query(id, "medal_id");
        fileName = ItemM.query(medalId, "icon");

        icon:loadTexture(getItemIconPath(fileName));
    elseif rule == "slime" then
        -- 英雄的图标
        local tech = SkyRelicFunctionM.query(id, "tech");
        local petId = tech["pet_id"];
        icon:loadTexture(getHeroIconPath(petId));
    elseif rule == "ariship_skill" then
        -- 秘宝图标
        local skillId = condition["skill_id"];
        icon:loadTexture(getAirShipSkillIconPath(skillId))
    else
        icon:loadTexture(getRelicFunctionIconPath(fileName));
    end

    local scale = SkyRelicFunctionM.query(id, "scale");
    if type(scale) == "number" and scale > 0 then
        icon:setScale(scale / 100);
    end

    if condition["skill_id"] then
        -- 秘宝，需要弹出详细页
        require "game/ui/form/sky_city/UIAirShipSkillDesc";
        icon:addTouchEventListener(function(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("workshop_material");
                local uishipSkillForm = UIAirShipSkillDesc.create(condition["skill_id"]);
                UIMgr:getCurrentScene():addForm(uishipSkillForm);
            end
        end);
        icon:setTouchEnabled(true);
    end

    local frame = item:getChildByName("frame");
    fileName = SkyRelicFunctionM.query(id, "bg");
    frame:loadTexture(getWorkshopStrengthenIconPath("bg3"));

    -- 是否可强化
    local canStrengthen = SkyRelicFunctionM.canDevelop(id);

    -- 等级
    local levelLabel = item:getChildByName("level");
    local color;

    if canStrengthen ~= true then
        color = TextStyleM.TEXT_COLOR_LIGHT_BLUE;
    else
        color = TextStyleM.TEXT_COLOR_BRIGHT_YELLOW;
    end
    TextStyleM.setTextStyle(levelLabel, 28, color, true, nil, nil, nil, nil, nil, true);
    TextStyleM.setShadowStyle(levelLabel, cc.size(0, -2.5));
    levelLabel:getVirtualRenderer():setAdditionalKerning(getLocKerning() -3);
    levelLabel:setPositionY(levelLabel:getPositionY() - 3);

    if level >= maxLevel then
        levelLabel:setString(getLocStr("level_max"));
    else
        levelLabel:setString(string.format(getLocStr("level_flag"), level));
    end

    -- 秘宝不显示LV.MAX
    if SkyRelicFunctionM.query(id, "rule") == "ariship_skill" then
        levelLabel:setVisible(false);
        btnBuy:setTitleText(getLocStr("make_combo_skill"));
    end

    if level == 0 then
        frame:setOpacity(96);
        icon:setOpacity(128);
        levelLabel:setVisible(false);
    end

    -- 花费
    self:initCost();

    -- 调整高度
    if not notAjust then
        self:adjustHeight();
    end
end

-- 花费
function UIRelicStrengthenDetail:initCost()
    local costLabel = findChildByName(self.node, "CT/cost");
    TextStyleM.setTextStyle(costLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, false);
    costLabel:getVirtualRenderer():setLineHeight(TextStyleM.TEXT_SIZE_SMALL + 5);

    local id = self.info.id;
    local level = SkyRelicFunctionM.getLevel(id);
    local cost = SkyRelicFunctionM.calcCost(id);

    local costStr = "";

    local function editCostStr(classId, count)
        local name, nameStr;
        local needNum = count;
        local curNum;
        local levelInfo;

        local function changeColor(current, need, str)
            -- 满足时显示蓝色，不足时显示红色
            if current < need then
                str = string.gsub(str, "{0}", "red");
            else
                str = string.gsub(str, "{0}", "blue");
            end

            return str;
        end

        if type(classId) == "number" then
            -- 物品
            name = ItemM.query(classId, "name");
            nameStr = string.format(getLocStr("need_money_amount"), name, needNum);
            curNum = ItemM.getAmount(ME.user, classId);

            local itemGroup = ItemM.query(classId, "group");
            if itemGroup == 35 then
                -- 能量晶核
                levelInfo = ItemM.query(classId, "unit");
                local level = FormulaM.invoke("CALC_ENERGY_NUCLEUS_LEVEL", classId);

                levelInfo = string.format(getLocStr("energy_nuclei_level"), levelInfo, level);
            end
        elseif type(classId) == "string" then
            -- 属性
            name = FieldsM.getFieldName(classId);
            nameStr = string.format(getLocStr("need_money_amount"), name, needNum);
            curNum = ME.user:queryAttrib(classId);
        end

        amountStr = "";
        amountStr = changeColor(curNum, needNum, amountStr);
        nameStr = changeColor(curNum, needNum, nameStr);


        if type(levelInfo) == "string" then
            costStr = costStr .. nameStr .. " " .. amountStr .. levelInfo .. "\n";
        else
            costStr = costStr .. nameStr .. " " .. amountStr .. "\n";
        end
    end

    local function sortCost(cost1, cost2)
        if type(cost1) ~= type(cost2) then
            if type(cost1) == "string" then
                return true;
            else
                return false;
            end
        else
            return cost1 < cost2;
        end
    end

    -- 编辑消耗
    local costIdList = table.keys(cost);
    table.sort(costIdList, sortCost);

    for index = 1, #costIdList do
        local id = costIdList[index];
        local amount = cost[id];

        editCostStr(id, amount);
    end

    -- 已升级到最大
    local maxLevel = self.info.max_level;
    if level >= maxLevel then
        if SkyRelicFunctionM.query(id, "rule") == "ariship_skill" then
            -- 秘宝显示已拥有
            costStr = getLocStr("has_own_combo_skill");
        else
            costStr = getLocStr("hint_reach_max_level");
        end
    end

    if level < maxLevel then
        -- 星阶限制
        if SkyRelicFunctionM.getLimitDesc(id) ~= "" then
            costStr = SkyRelicFunctionM.getLimitDesc(id);
        end

        local condition = SkyRelicFunctionM.query(self.info.id, "condition");
        if condition["skill_id"] and condition["awake_slime"] then
            -- 圣器特别处理
            -- 操控该秘宝的冈布奥需要建造雕像
            local can = true;
            for _, petId in ipairs(condition["awake_slime"]) do
                if not AwakeM.isCarved(petId) then
                    can = false;
                    break;
                end
            end
            if can then
                costStr = costStr .. getLocStr("awake_skill_create_cond");
            else
                costStr = costStr .. "[red]" .. getLocStr("awake_skill_create_cond") .. "[-]";
            end
        end
    end
    applyString(costLabel, costStr);
end

-- 调整高度
function UIRelicStrengthenDetail:adjustHeight()
    local CT = findChildByName(self.node, "CT");
    local costLabel = findChildByName(self.node, "CT/cost");
    local lineNum = costLabel:getVirtualRenderer():getStringNumLines();

    local delta = (3 - lineNum) * TextStyleM.TEXT_SIZE_SMALL;
    if delta == 0 then
        return;
    end

    costLabel:setPositionY(costLabel:getPositionY() + delta / 2);

    local btnBuy = findChildByName(self.node, "CT/strengthen");
    btnBuy:setPositionY(btnBuy:getPositionY() + delta);

    local bg = findChildByName(self.node, "CT/template/bg");
    local bgDelta = delta / bg:getScaleY();
    local bg3 = findChildByName(self.node, "CT/template/bg/bg3");
    local bg4 = findChildByName(self.node, "CT/template/bg/bg4");
    if delta > 0 then
        bg3:setPositionY(bg3:getPositionY() + bgDelta);
        bg4:setPositionY(bg4:getPositionY() + bgDelta);
    else
        bg3:setScaleY((getRealContentSize(bg3).height - bgDelta)/getRealContentSize(bg3).height);
        bg4:setScaleY((getRealContentSize(bg4).height - bgDelta)/getRealContentSize(bg4).height);
        -- 整体需要上移
        self.bgDelta = bgDelta;
    end
end

-- 适配
function UIRelicStrengthenDetail:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    local CT = findChildByName(node, "CT");
    if self.bgDelta then
        -- 上移
        CT:setPositionY(CT:getPositionY() - self.bgDelta/2);
    end

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end


